package com.zenchn.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zenchn.annotation.OperLog;
import com.zenchn.entity.*;
import com.zenchn.enums.DictTypeEnum;
import com.zenchn.enums.OperLogActionEnum;
import com.zenchn.enums.SessionAttributeEnum;
import com.zenchn.exception.CheckException;
import com.zenchn.model.*;
import com.zenchn.service.*;
import com.zenchn.utils.CommonUtils;
import com.zenchn.utils.PwdHashSaltUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 微信接口
 * @author wlf
 * @version 1.0
 * @date 2021/6/5 23:56:44
 */
@RestController
@RequestMapping(value = "wx")
@Api(value = "微信接口", tags = "微信接口")
@RequiresAuthentication
public class WeixinController {

    private final String MODULE = "微信接口";

    @Resource
    private RegionDetailService regionDetailService;

    @Resource
    private AreasService areasService;

    @Resource
    private RegionService regionService;

    @Resource
    private CustomerUpgradeService upgradeService;

    @Resource
    private DictService dictService;

    @Resource
    private CustomerService customerService;

    @Resource
    private CustomerContactsService customerContactsService;

    @Resource
    private CustomerVisitService customerVisitService;

    @Resource
    private SysFileService sysFileService;

    @Resource
    private SysConfig sysConfig;

    @Resource
    private AccountService accountService;

    @Resource
    private CustomerCompletionService customerCompletionService;

    @Resource
    private CustomerTransferService customerTransferService;


    @Resource
    private ConfigService configService;

    /**
     * 我的-获取用户业务数据
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取用户业务数据", isSaveRequestData = false)
    @ApiOperation(value = "获取用户业务数据", notes = "获取用户业务数据")
    @PostMapping(value = "/getBusinessData")
    public ResponseEntity<HttpDataResult<IndexVO>> getBusinessData(
            @RequestBody TimeSearchDO timeDO,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<IndexVO> result = new HttpDataResult<>(request.getRequestURI());

        LocalDate time = timeDO.getTime();
        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        IndexVO vo = new IndexVO();

        List<TSysDict> dictList = getAccountLevel();
        String firstAccountLevel = dictList.get(0).getDictId();
        List<String> areaCodeList = getAreaCodeList(firstAccountLevel,accountExtend);

        TMiCustomerExample customerExample = new TMiCustomerExample();
        TMiCustomerExample.Criteria criteria = customerExample.createCriteria();
        if(areaCodeList!=null &&!areaCodeList.isEmpty() && time!=null){

            //目标
            if(checkThisMonth(time)){
                BeanUtils.copyProperties(accountExtend,vo);
            }else{
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMM");
                String timeStr = df.format(time);
                TMiCustomerCompletionExample example = new TMiCustomerCompletionExample();
                example.createCriteria().andMonthEqualTo(timeStr).andAccountIdEqualTo(accountExtend.getAccountId());
                List<TMiCustomerCompletion> tMiCustomerCompletions = customerCompletionService.selectByExample(example);
                if(tMiCustomerCompletions!=null && !tMiCustomerCompletions.isEmpty()){
                    TMiCustomerCompletion tMiCustomerCompletion = tMiCustomerCompletions.get(0);
                    BeanUtils.copyProperties(tMiCustomerCompletion,vo);
                }
            }

            criteria.andAreasCodeIn(areaCodeList).andAccountIdEqualTo(accountExtend.getAccountId());
            List<TMiCustomer> customers = customerService.selectByExample(customerExample);
            if(customers!=null && !customers.isEmpty()){
                List<String> customerIdList = customers.stream().map(TMiCustomer::getCustomerId).collect(Collectors.toList());

                //获取完成情况
                Map<String, String> customerMap = customers.stream().collect(Collectors.toMap(TMiCustomer::getCustomerId, TMiCustomer::getCustomerType));

                //如果是本月 获取实时业绩完成情况
                if(checkThisMonth(time)){
                    //本月
                    int agentCompletion = 0;
                    int agentL2Completion = 0;
                    int agentL3Completion = 0;
                    int hospitalCompletion = 0;
                    int hospitalL2Completion = 0;
                    int hospitalL3Completion = 0;
                    int agentVisit = 0;
                    int hospitalVisit = 0;
                    for (TMiCustomer customer : customers) {
                        if(checkThisMonth(customer.getCreateTime())){
                            if("1".equals(customer.getCustomerType())){
                                agentCompletion++;
                            }else if("2".equals(customer.getCustomerType())){
                                hospitalCompletion++;
                            }
                        }
                    }
                    //升级逻辑
                    TMiCustomerUpgradeExample upgradeExample = new TMiCustomerUpgradeExample();
                    upgradeExample.createCriteria().andCustomerIdIn(customerIdList)
                            .andCreatorEqualTo(accountExtend.getAccountId())
                            .andUpgradeTypeEqualTo("1").andIsEnableEqualTo("1")
                            .andCreateTimeBetween(getMonthFirstTime(time),getMonthLastTime(time));
                    List<TMiCustomerUpgrade> tMiCustomerUpgrades = upgradeService.selectByExample(upgradeExample);
                    for (TMiCustomerUpgrade customerUpgrade : tMiCustomerUpgrades) {
                        String type = customerMap.get(customerUpgrade.getCustomerId());
                        if(type!=null && !"".equals(type)){
                            if(customerUpgrade.getBeforeLevel()==1 && customerUpgrade.getUpgradeLevel()==2){
                                if("1".equals(type)){
                                    agentL2Completion++;
                                }else if("2".equals(type)){
                                    hospitalL2Completion++;
                                }
                            }
                            if(customerUpgrade.getBeforeLevel()==2 && customerUpgrade.getUpgradeLevel()==3){
                                if("1".equals(type)){
                                    agentL3Completion++;
                                }else if("2".equals(type)){
                                    hospitalL3Completion++;
                                }
                            }
                        }
                    }
                    //获取拜访信息记录
                    VisitCountBO visitCount = customerVisitService.getCustomerVisit(getMonthFirstDate(time), getNextMonthFirstDate(time), accountExtend.getAccountId());
                    if(visitCount!=null){
                        agentVisit = visitCount.getAgentVisit();
                        hospitalVisit = visitCount.getHospitalVisit();
                    }

                    vo.setAgentVisit(agentVisit);
                    vo.setHospitalVisit(hospitalVisit);
                    vo.setAgentCompletion(agentCompletion);
                    vo.setAgentL2Completion(agentL2Completion);
                    vo.setAgentL3Completion(agentL3Completion);
                    vo.setHospitalCompletion(hospitalCompletion);
                    vo.setHospitalL2Completion(hospitalL2Completion);
                    vo.setHospitalL3Completion(hospitalL3Completion);
                }


            }

            //为空 赋值
            checkObjFieldIsNull(vo);

            //构建百分比
            vo.setAgentCompletionRate(twoDecimalDivision(vo.getAgentCompletion(),vo.getAgentTarget()));
            vo.setAgentL2CompletionRate(twoDecimalDivision(vo.getAgentL2Completion(),vo.getAgentL2Target()));
            vo.setAgentL3CompletionRate(twoDecimalDivision(vo.getAgentL3Completion(),vo.getAgentL3Target()));
            vo.setHospitalCompletionRate(twoDecimalDivision(vo.getHospitalCompletion(),vo.getHospitalTarget()));
            vo.setHospitalL2CompletionRate(twoDecimalDivision(vo.getHospitalL2Completion(),vo.getHospitalL2Target()));
            vo.setHospitalL3CompletionRate(twoDecimalDivision(vo.getHospitalL3Completion(),vo.getHospitalL3Target()));
        }

        result.setData(vo);
        result.setMessage("获取用户业务数据成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    public void checkObjFieldIsNull(Object obj){
        try{
            for(Field f : obj.getClass().getDeclaredFields()){
                f.setAccessible(true);
                if(f.get(obj) == null){
                    if(Integer.class == f.getType()){
                        f.set(obj,0);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private Double twoDecimalDivision(Integer a,Integer b){
        String value;
        if(a==null || b == null){
            value = "0.00";
        }else{
            if(a>b || b==0){
                if(a==0){
                    value = "0.00";
                }else{
                    value = "100.00";
                }
            }else{
                DecimalFormat df = new DecimalFormat("0.00");
                value = df.format((float) a / b * 100);
            }
        }
        return Double.valueOf(value);
    }

    private LocalDateTime getMonthFirstTime(LocalDate nowDate){
        LocalDateTime nowTime = LocalDateTime.of(nowDate,LocalTime.MIN);
        return nowTime.with(TemporalAdjusters.firstDayOfMonth());
    }

    private LocalDate getMonthFirstDate(LocalDate nowDate){
        return nowDate.with(TemporalAdjusters.firstDayOfMonth());
    }

    private LocalDateTime getMonthLastTime(LocalDate nowDate){
        LocalDateTime nowTime = LocalDateTime.of(nowDate,LocalTime.MIN);
        return nowTime.with(TemporalAdjusters.lastDayOfMonth());
    }

    private LocalDate getNextMonthFirstDate(LocalDate nowDate){
        LocalDate lastDay = nowDate.with(TemporalAdjusters.lastDayOfMonth());
        return lastDay.plusDays(1);
    }

    private boolean checkThisMonth(LocalDate date){
        LocalDate nowDate = LocalDate.now();
        return nowDate.getYear() == date.getYear() && nowDate.getMonthValue() == date.getMonthValue();
    }

    private boolean checkThisMonth(LocalDateTime time){
        LocalDate date = time.toLocalDate();
        LocalDate nowDate = LocalDate.now();
        return nowDate.getYear() == date.getYear() && nowDate.getMonthValue() == date.getMonthValue();
    }


    /**
     * 微信用户信息
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "微信用户信息", notes = "微信用户信息")
    @GetMapping(value = "/current")
    public ResponseEntity<HttpDataResult<AccountVO>> current(HttpServletRequest request, HttpServletResponse response) {
        HttpDataResult<AccountVO> result = new HttpDataResult<>(request.getRequestURI());

        TSysAccount account = (TSysAccount)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_INFO.getKey());
        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());

        //登录人头像
        String url = (String)request.getSession().getAttribute(SessionAttributeEnum.PORTRAIT_URL.getKey());
        if(url == null || "".equals(url)){
            if (null != account.getPortraitFileId() && !"".equals(account.getPortraitFileId())) {
                TSysFile sf = sysFileService.selectByPrimaryKey(account.getPortraitFileId());
                if (null != sf) {
                    url = sysConfig.getCurrentUseFormalFileUrl() + "/" + sf.getFilePath();
                    request.getSession().setAttribute(SessionAttributeEnum.PORTRAIT_URL.getKey(), url);
                }
            }
        }
        AccountVO vo = new AccountVO();
        vo.setPortraitUrl(url);
        BeanUtils.copyProperties(account,vo);
        TSysDict dict = dictService.selectByPrimaryKey(accountExtend.getAccountLevel());
        if(dict!=null){
            vo.setAccountLevel(dict.getDictCode());
        }

        if(accountExtend.getAreasCode()!=null && !"".equals(accountExtend.getAreasCode())){
            TSysAreas tSysAreas = areasService.selectByPrimaryKey(accountExtend.getAreasCode());
            if(tSysAreas!=null){
                vo.setAreaName(tSysAreas.getFullName());
            }
        }

        if(accountExtend.getRegionCode()!=null && !"".equals(accountExtend.getRegionCode())){
            TMiRegion tMiRegion = regionService.selectByPrimaryKey(accountExtend.getRegionCode());
            if(tMiRegion!=null){
                vo.setRegionName(tMiRegion.getRegionName());
                StringBuilder sb = new StringBuilder();
                if(!StringUtils.isBlank(tMiRegion.getRegionId())){
                    List<String> tMiRegionDetails = regionDetailService.getAreaNames(tMiRegion.getRegionId());
                    if(tMiRegionDetails!=null && !tMiRegionDetails.isEmpty()){
                        tMiRegionDetails.forEach(item-> sb.append(item).append("、"));
                        sb.deleteCharAt(sb.length() - 1);
                        vo.setAreaName(sb.toString());
                    }
                }
            }
        }

        result.setData(vo);
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 我的-更新用户数据
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.UPDATE, detail = "更新用户数据", isSaveRequestData = false)
    @ApiOperation(value = "更新用户数据", notes = "更新用户数据")
    @PostMapping(value = "/updateUser")
    public ResponseEntity<HttpDataResult<Boolean>> updateUser(
            @RequestBody TSysAccount account,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        if(!accountExtend.getAccountId().equals(account.getAccountId())){
            throw new CheckException("账号信息不一致，请重新登陆！");
        }

        TSysAccount accountInfo = accountService.selectByPrimaryKey(account.getAccountId());
        if(accountInfo==null){
            throw new CheckException("账号不存在，请重新登陆！");
        }
        accountInfo.setRealName(account.getRealName());
        accountInfo.setSex(account.getSex());
        accountInfo.setEmail(account.getEmail());
        accountInfo.setTel(account.getTel());

        accountService.updateByPrimaryKey(accountInfo);


        result.setData(true);
        result.setMessage("更新用户数据成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 我的-检查密码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "检查密码", isSaveRequestData = false)
    @ApiOperation(value = "检查密码", notes = "检查密码")
    @PostMapping(value = "/checkPwd")
    public ResponseEntity<HttpDataResult<Boolean>> checkPwd(
            @RequestBody String password,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        TSysAccount account = (TSysAccount)request.getSession().getAttribute(SessionAttributeEnum. CURRENT_ACCOUNT_INFO.getKey());
        if(account==null){
            throw new CheckException("账号不存在，请重新登陆！");
        }
        String pwd = account.getPassword();

        String spwd = PwdHashSaltUtils.againSha256Hex(account.getAccount(),CommonUtils.sha256Hex(password));

        result.setData(pwd.equals(spwd));
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 我的-修改密码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.UPDATE, detail = "修改密码", isSaveRequestData = false)
    @ApiOperation(value = "修改密码", notes = "修改密码")
    @PostMapping(value = "/updatePwd")
    public ResponseEntity<HttpDataResult<Boolean>> updatePwd(
            @RequestBody UpdatePwdDO passwordDO,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        TSysAccount account = (TSysAccount)request.getSession().getAttribute(SessionAttributeEnum. CURRENT_ACCOUNT_INFO.getKey());
        if(account==null){
            throw new CheckException("账号不存在，请重新登陆！");
        }
        String pwd = account.getPassword();

        String spwd = PwdHashSaltUtils.againSha256Hex(account.getAccount(),CommonUtils.sha256Hex(passwordDO.getOldPwd()));
        if(pwd.equals(spwd)){
            String newPwd = PwdHashSaltUtils.againSha256Hex(account.getAccount(),CommonUtils.sha256Hex(passwordDO.getNewPwd()));
            account.setPassword(newPwd);
            accountService.updateByPrimaryKey(account);
        }else{
            throw new CheckException("原密码错误，请重新输入！");
        }

        result.setData(true);
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息添加-获取登录账号包含所属省份
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取登录账号包含所属省份", isSaveRequestData = false)
    @ApiOperation(value = "获取登录账号包含所属省份", notes = "获取登录账号包含所属省份")
    @GetMapping(value = "/areaList")
    public ResponseEntity<HttpDataResult<List<AccountAreaVO>>> areaList(
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<List<AccountAreaVO>> result = new HttpDataResult<>(request.getRequestURI());

        List<AccountAreaVO> list = new ArrayList<>();

        //区域等级字典表
        List<TSysDict> dictList = getAccountLevel();
        String firstAccountLevel = dictList.get(0).getDictId();

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        List<String> areaCodeList = getAreaCodeList(firstAccountLevel,accountExtend);
        if(areaCodeList==null || areaCodeList.isEmpty()){
            throw new CheckException("无区域权限！");
        }

        //获取地区名字和code
        TSysAreasExample areasExample = new TSysAreasExample();
        areasExample.createCriteria().andCodeIn(areaCodeList);
        List<TSysAreas> tSysAreas = areasService.selectByExample(areasExample);
        Map<String, String> areaNameMap = tSysAreas.stream().collect(Collectors.toMap(TSysAreas::getCode, TSysAreas::getName));
        if (!areaCodeList.isEmpty()){
            for (String areaCode : areaCodeList) {
                list.add(new AccountAreaVO(areaCode,areaNameMap.get(areaCode)));
            }
        }

        result.setData(list);

        result.setMessage("获取省份列表成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息添加-获取登录账号包含代理商
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取登录账号包含代理商", isSaveRequestData = false)
    @ApiOperation(value = "获取登录账号包含代理商", notes = "获取登录账号包含代理商")
    @GetMapping(value = "/agentList")
    public ResponseEntity<HttpDataResult<List<AccountAgentVO>>> agentList(
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<List<AccountAgentVO>> result = new HttpDataResult<>(request.getRequestURI());

        List<AccountAgentVO> list = new ArrayList<>();
        list.add(new AccountAgentVO("00000000000000000000000000000000","杭州鼎诺医疗设备有限公司"));

        //区域等级字典表
        List<TSysDict> dictList = getAccountLevel();
        String firstAccountLevel = dictList.get(0).getDictId();

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        List<String> areaCodeList = getAreaCodeList(firstAccountLevel,accountExtend);

        //获取代理商
        if (!areaCodeList.isEmpty()){
            TMiCustomerExample example = new TMiCustomerExample();
            example.createCriteria().andAreasCodeIn(areaCodeList).andCustomerTypeEqualTo("1").andLevelGreaterThanOrEqualTo(4).andCustomerIdNotEqualTo("00000000000000000000000000000000");
            List<TMiCustomer> customers = customerService.selectByExample(example);
            if(customers!=null && !customers.isEmpty()){
                for (TMiCustomer customer : customers) {
                    list.add(new AccountAgentVO(customer.getCustomerId(),customer.getCustomerName()));
                }
            }
        }

        result.setData(list);

        result.setMessage("获取代理商列表成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /**
     * 客户信息添加-提交客户信息
     * @param customerDO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.INSERT,detail="提交客户信息")
    @ApiOperation(value = "提交客户信息", notes = "提交客户信息")
    @ApiParam( type = "TMiCustomerDO",name = "customerDO", value = "客户对象", required = true)
    @PostMapping(value = "/addCustomer")
    public ResponseEntity<HttpDataResult<String>> addCustomer(
            @RequestBody @Valid TMiCustomerDO customerDO, BindingResult results,
            HttpServletRequest request, HttpServletResponse response) throws Exception{

        if (results.hasErrors()){
            throw new CheckException(Objects.requireNonNull(results.getFieldError()).getDefaultMessage());
        }

        if (!customerService.checkExistCustomer(customerDO.getCustomerName())){
            throw new CheckException("该客户已存在，无法新增提交！");
        }
        List<TMiCustomerContacts> contactList = customerDO.getContactList();
        HashSet<String> phoneSet = new HashSet<>();
        for (TMiCustomerContacts tMiCustomerContacts : contactList) {
            if (phoneSet.contains(tMiCustomerContacts.getTelephone().trim())) {
                throw new CheckException("联系人存在重复手机号");
            } else {
                phoneSet.add(tMiCustomerContacts.getTelephone().trim());
            }
        }

        HttpDataResult<String> result = new HttpDataResult<>(request.getRequestURI());

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        String accountId = accountExtend.getAccountId();

        TMiCustomer customer = new TMiCustomer();
        String customerId = CommonUtils.randomUUID();
        customer.setCustomerId(customerId);
        customer.setCustomerType(customerDO.getCustomerType());
        customer.setAreasCode(customerDO.getAreasCode());
        customer.setCustomerName(customerDO.getCustomerName());
        customer.setCustomerAdress(customerDO.getCustomerAdress());
        customer.setBusiness(customerDO.getBusiness());
        customer.setRegion(customerDO.getRegion());
        customer.setNet(customerDO.getNet());
        customer.setLevel(1);
        customer.setAccountId(accountId);
        customer.setCreator(accountId);
        customer.setCreateTime(LocalDateTime.now());
        if("1".equals(customerDO.getCustomerType())){
            customer.setBelongTo(null);
        }else if("2".equals(customerDO.getCustomerType())){
            if(StringUtils.isBlank(customerDO.getBelongTo())){
                throw new CheckException("医院关联代理商不可为空！");
            }else{
                customer.setBelongTo(customerDO.getBelongTo());
            }
        }

        customerService.insertSelective(customer);

        for (int i = 0; i < contactList.size(); i++) {
            TMiCustomerContacts customerContacts = contactList.get(i);
            customerContacts.setContactsId(CommonUtils.randomUUID());
            customerContacts.setCustomerId(customerId);
            if(i==0){
                customerContacts.setIsDefault("1");
            }
            customerContacts.setCreator(accountId);
            customerContacts.setCreateTime(LocalDateTime.now());
            customerContactsService.insert(customerContacts);
        }

        result.setData(customerId);
        result.setMessage("新增客户成功。");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户拜访-获取操作记录信息
     * @param list
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.QUERY,detail="获取操作记录信息")
    @ApiOperation(value = "获取操作记录信息", notes = "获取操作记录信息")
    @ApiParam( type = "List",name = "list", value = "查询记录列表", required = true)
    @PostMapping(value = "/searchList")
    public ResponseEntity<HttpDataResult<List<TMiCustomer>>> searchList(
            @RequestBody @Valid List<String> list, BindingResult results,
            HttpServletRequest request, HttpServletResponse response) throws Exception{

        HttpDataResult<List<TMiCustomer>> result = new HttpDataResult<>(request.getRequestURI());

        //区域等级字典表
        List<TSysDict> dictList = getAccountLevel();
        String firstAccountLevel = dictList.get(0).getDictId();

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());

        List<String> areaCodeList = getAreaCodeList(firstAccountLevel,accountExtend);

        List<TMiCustomer> tMiCustomers = new ArrayList<>();
        if(!areaCodeList.isEmpty() && list!=null && !list.isEmpty()){
            TMiCustomerExample example = new TMiCustomerExample();
            TMiCustomerExample.Criteria criteria = example.createCriteria();
            if(accountExtend.getAccountLevel().equals(firstAccountLevel)){
                criteria.andAccountIdEqualTo(accountExtend.getAccountId());
            }
            criteria.andAreasCodeIn(areaCodeList).andCustomerIdIn(list);
            tMiCustomers = customerService.selectByExample(example);
        }

        result.setData(tMiCustomers);
        result.setMessage("获取操作记录信息成功。");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户拜访-获取操作记录信息
     * @param searchClientDO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.QUERY,detail="查询代理商医院信息")
    @ApiOperation(value = "查询代理商医院信息", notes = "查询代理商医院信息")
    @ApiParam( type = "String",name = "keyWord", value = "查询记录列表", required = true)
    @PostMapping(value = "/searchClient")
    public ResponseEntity<HttpDataResult<PageInfo<TMiCustomer>>> searchClient(
            @RequestBody SearchClientDO searchClientDO,
            HttpServletRequest request, HttpServletResponse response) throws Exception{

        HttpDataResult<PageInfo<TMiCustomer>> result = new HttpDataResult<>(request.getRequestURI());

        //区域等级字典表
        List<TSysDict> dictList = getAccountLevel();
        String firstAccountLevel = dictList.get(0).getDictId();
        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        List<String> areaCodeList = getAreaCodeList(firstAccountLevel,accountExtend);
        if(areaCodeList==null || areaCodeList.isEmpty()){
            throw new CheckException("无区域权限！");
        }

        TMiCustomerExample example = new TMiCustomerExample();
        TMiCustomerExample.Criteria criteria = example.createCriteria();
        if(accountExtend.getAccountLevel().equals(firstAccountLevel)){
            criteria.andAccountIdEqualTo(accountExtend.getAccountId());
        }
        criteria.andAreasCodeIn(areaCodeList);
        if(searchClientDO.getKeyWord()!=null && !"".equals(searchClientDO.getKeyWord().trim()) ){
            criteria.andCustomerNameLike('%'+searchClientDO.getKeyWord()+'%');
        }
        PageHelper.startPage(searchClientDO.getPageIndex(), searchClientDO.getPageSize());
        PageInfo<TMiCustomer> pageInfo = new PageInfo<>(customerService.selectByExample(example));


        result.setData(pageInfo);
        result.setMessage("查询代理商医院信息成功。");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 拜访记录-获取拜访信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取拜访信息", isSaveRequestData = false)
    @ApiOperation(value = "获取拜访信息", notes = "获取拜访信息")
    @PostMapping(value = "/getVisitInfo")
    public ResponseEntity<HttpDataResult<TMiCustomerVisitVO>> getVisitInfo(
            @RequestBody String visitId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<TMiCustomerVisitVO> result = new HttpDataResult<>(request.getRequestURI());

        TMiCustomerVisitVO vo= new TMiCustomerVisitVO();

        TMiCustomerVisit customerVisit = customerVisitService.selectByPrimaryKey(visitId);
        if(customerVisit!=null){
            BeanUtils.copyProperties(customerVisit,vo);
            TMiCustomerContacts customerContacts = customerContactsService.selectByPrimaryKey(customerVisit.getContactsId());
            if(customerContacts!=null){
                vo.setContactsName(customerContacts.getContactsName());
                vo.setTelephone(customerContacts.getTelephone());
            }
        }

        result.setData(vo);
        result.setMessage("获取拜访信息成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 拜访记录-获取客户信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取客户信息", isSaveRequestData = false)
    @ApiOperation(value = "获取客户信息", notes = "获取客户信息")
    @PostMapping(value = "/customerInfo")
    public ResponseEntity<HttpDataResult<TMiCustomer>> customerInfo(
            @RequestBody String id,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<TMiCustomer> result = new HttpDataResult<>(request.getRequestURI());

        TMiCustomer customer = customerService.selectByPrimaryKey(id);

        result.setData(customer);
        result.setMessage("获取客户信息成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 拜访记录-判断代理商是否有医院
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "判断代理商是否有医院", isSaveRequestData = false)
    @ApiOperation(value = "判断代理商是否有医院", notes = "判断代理商是否有医院")
    @PostMapping(value = "/checkHasHospital")
    public ResponseEntity<HttpDataResult<Boolean>> checkHasHospital(
            @RequestBody String id,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        TMiCustomerExample example = new TMiCustomerExample();
        example.createCriteria().andBelongToEqualTo(id).andCustomerTypeEqualTo("2");
        List<TMiCustomer> customers = customerService.selectByExample(example);
        if(customers!=null && !customers.isEmpty()){
            result.setData(true);
        }else{
            result.setData(false);
        }

        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 拜访记录-获取客户访问记录
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取客户访问记录", isSaveRequestData = false)
    @ApiOperation(value = "获取客户访问记录", notes = "获取客户访问记录")
    @PostMapping(value = "/customerVisit")
    public ResponseEntity<HttpDataResult<List<DateListVO<CustomerVistitContactsVO>>>> customerVisit(
            @RequestBody String id,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<List<DateListVO<CustomerVistitContactsVO>>> result = new HttpDataResult<>(request.getRequestURI());

        List<DateListVO<CustomerVistitContactsVO>> dateList = new ArrayList<>();

        TMiCustomerVisitExample visitExample = new TMiCustomerVisitExample();
        visitExample.createCriteria().andCustomerIdEqualTo(id);
        visitExample.setOrderByClause("create_time DESC");
        List<TMiCustomerVisit> customerVisitList = customerVisitService.selectByExample(visitExample);

        if(customerVisitList!=null && !customerVisitList.isEmpty()){
            List<String> contactIdList = customerVisitList.stream().map(TMiCustomerVisit::getContactsId).collect(Collectors.toList());
            TMiCustomerContactsExample contactsExample = new TMiCustomerContactsExample();
            contactsExample.createCriteria().andContactsIdIn(contactIdList);
            List<TMiCustomerContacts> customerContacts = customerContactsService.selectByExample(contactsExample);
            Map<String,TMiCustomerContacts> map = new HashMap<>();
            for (TMiCustomerContacts customerContact : customerContacts) {
                map.put(customerContact.getContactsId(),customerContact);
            }
            LocalDate lastDate = null;
            int index = -1;
            for (TMiCustomerVisit customerVisit : customerVisitList) {
                if(lastDate == null || !lastDate.equals(customerVisit.getVisitDate()) ){
                    index++;
                    dateList.add(new DateListVO<>(customerVisit.getVisitDate(),new ArrayList<>()));
                    lastDate = customerVisit.getVisitDate();
                }
                dateList.get(index).getList().add(new CustomerVistitContactsVO(customerVisit,map.get(customerVisit.getContactsId())));
            }
        }

        result.setData(dateList);
        result.setMessage("获取客户访问记录成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 拜访记录-获取客户联系人列表
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取客户联系人列表", isSaveRequestData = false)
    @ApiOperation(value = "获取客户联系人列表", notes = "获取客户联系人列表")
    @PostMapping(value = "/concatList")
    public ResponseEntity<HttpDataResult<List<TMiCustomerContacts>>> concatList(
            @RequestBody String id,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<List<TMiCustomerContacts>> result = new HttpDataResult<>(request.getRequestURI());

        TMiCustomerContactsExample example = new TMiCustomerContactsExample();
        example.createCriteria().andCustomerIdEqualTo(id);
        example.setOrderByClause("is_default DESC");
        List<TMiCustomerContacts> customerContacts = customerContactsService.selectByExample(example);

        result.setData(customerContacts);
        result.setMessage("获取客户联系人列表成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 拜访记录-获取可添加的客户联系人列表
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取可添加的客户联系人列表", isSaveRequestData = false)
    @ApiOperation(value = "获取可添加的客户联系人列表", notes = "获取可添加的客户联系人列表")
    @PostMapping(value = "/couldVisitConcatList")
    public ResponseEntity<HttpDataResult<List<CustomerVisitSelectVO>>> couldVisitConcatList(
            @RequestBody String id,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<List<CustomerVisitSelectVO>> result = new HttpDataResult<>(request.getRequestURI());
        List<CustomerVisitSelectVO> voList = new ArrayList<>();

        TMiCustomerVisitExample visitExample = new TMiCustomerVisitExample();
        visitExample.createCriteria().andCustomerIdEqualTo(id).andVisitDateEqualTo(LocalDate.now());
        List<TMiCustomerVisit> customerVisitList = customerVisitService.selectByExample(visitExample);
        Set<String> constantIdSet = new HashSet<>();
        if(customerVisitList!=null && !customerVisitList.isEmpty()){
            constantIdSet = customerVisitList.stream().map(TMiCustomerVisit::getContactsId).collect(Collectors.toSet());
        }

        TMiCustomerContactsExample example = new TMiCustomerContactsExample();
        example.createCriteria().andCustomerIdEqualTo(id);
        example.setOrderByClause("is_default DESC");
        List<TMiCustomerContacts> customerContacts = customerContactsService.selectByExample(example);
        if(customerContacts!=null && !customerContacts.isEmpty()){
            for (TMiCustomerContacts customerContact : customerContacts) {
                CustomerVisitSelectVO vo = new CustomerVisitSelectVO();
                BeanUtils.copyProperties(customerContact,vo);
                if(!constantIdSet.isEmpty() && constantIdSet.contains(customerContact.getContactsId())){
                    vo.setCanSelect(false);
                }else{
                    vo.setCanSelect(true);
                }
                voList.add(vo);
            }
        }

        result.setData(voList);
        result.setMessage("获取可添加的客户联系人列表成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /**
     * 拜访记录-提交拜访信息
     * @param customerVisit
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.INSERT,detail="提交拜访信息")
    @ApiOperation(value = "提交拜访信息", notes = "提交拜访信息")
    @ApiParam( type = "TMiCustomerVisit",name = "customerVisit", value = "拜访信息对象", required = true)
    @PostMapping(value = "/addVisit")
    public ResponseEntity<HttpDataResult<Boolean>> addVisit(
            @RequestBody @Valid TMiCustomerVisit customerVisit, BindingResult results,
            HttpServletRequest request, HttpServletResponse response) throws Exception{

        if (results.hasErrors()){
            throw new CheckException(Objects.requireNonNull(results.getFieldError()).getDefaultMessage());
        }

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());

        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        customerVisit.setVisitId(CommonUtils.randomUUID());
        customerVisit.setVisitDate(LocalDate.now());
        customerVisit.setCreator(accountExtend.getAccountId());
        customerVisit.setCreateTime(LocalDateTime.now());
        customerVisitService.insertSelective(customerVisit);

        result.setData(true);
        result.setMessage("提交拜访信息成功。");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /**
     * 拜访记录-修改拜访信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.INSERT,detail="修改拜访信息")
    @ApiOperation(value = "修改拜访信息", notes = "修改拜访信息")
    @ApiParam( type = "TMiCustomerVisit",name = "customerVisit", value = "拜访信息对象", required = true)
    @PostMapping(value = "/editVisit")
    public ResponseEntity<HttpDataResult<Boolean>> editVisit(
            @RequestBody @Valid VisitEditDO visitEditDO,
            HttpServletRequest request, HttpServletResponse response) throws Exception{

        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());
        TMiCustomerVisit oldCustomerVisit = customerVisitService.selectByPrimaryKey(visitEditDO.getVisitId());
        if(oldCustomerVisit==null){
            throw new CheckException("拜访记录不存在");
        }

        oldCustomerVisit.setContent(visitEditDO.getContent());
        oldCustomerVisit.setChance(visitEditDO.getChance());
        oldCustomerVisit.setAskForHelp(visitEditDO.getAskForHelp());
        customerVisitService.updateByPrimaryKey(oldCustomerVisit);

        result.setData(true);
        result.setMessage("修改拜访信息成功。");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息管理-查询代理商医院信息
     * @param searchClientDO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.QUERY,detail="查询代理商医院信息")
    @ApiOperation(value = "查询代理商医院信息", notes = "查询代理商医院信息")
    @ApiParam( type = "String",name = "keyWord", value = "查询记录列表", required = true)
    @PostMapping(value = "/advancedSearchClient")
    public ResponseEntity<HttpDataResult<PageInfo<TMiCustomer>>> advancedSearchClient(
            @RequestBody SearchClientDO searchClientDO,
            HttpServletRequest request, HttpServletResponse response) throws Exception{

        HttpDataResult<PageInfo<TMiCustomer>> result = new HttpDataResult<>(request.getRequestURI());

        TMiCustomerExample example = new TMiCustomerExample();
        TMiCustomerExample.Criteria criteria = example.createCriteria();

        //区域等级字典表
        List<TSysDict> dictList = getAccountLevel();
        String firstAccountLevel = dictList.get(0).getDictId();
        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        List<String> areaCodeList = getAreaCodeList(firstAccountLevel,accountExtend);
        if(areaCodeList==null || areaCodeList.isEmpty()){
            throw new CheckException("无区域权限！");
        }

        /* 区域 **/
        if(searchClientDO.getAreaCode()!=null && !"".equals(searchClientDO.getAreaCode())){
            if(areaCodeList.contains(searchClientDO.getAreaCode().trim())){
                criteria.andAreasCodeEqualTo(searchClientDO.getAreaCode().trim());
            }else{
                throw new CheckException("该省份不在账户权限范围内,请重试！");
            }
        }else{
            criteria.andAreasCodeIn(areaCodeList);
        }

        /* 录入开始时间 **/
        if(searchClientDO.getStartDate()!=null){
            LocalDateTime time = LocalDateTime.of(searchClientDO.getStartDate(), LocalTime.MIN);
            criteria.andCreateTimeGreaterThanOrEqualTo(time);
        }

        /* 录入结束时间 **/
        if(searchClientDO.getEndDate()!=null){
            LocalDateTime time = LocalDateTime.of(searchClientDO.getEndDate(), LocalTime.MAX);
            criteria.andCreateTimeLessThanOrEqualTo(time);
        }

        /* 类型 **/
        if(searchClientDO.getCustomerType()!=null && !"".equals(searchClientDO.getCustomerType().trim())){
            criteria.andCustomerTypeEqualTo(searchClientDO.getCustomerType());
        }

        /* 等级 **/
        if(searchClientDO.getLevel()!=null){
            criteria.andLevelEqualTo(searchClientDO.getLevel());
        }
        /* 权限 **/
        TSysDict tSysDict = dictService.selectByPrimaryKey(accountExtend.getAccountLevel());
        if(tSysDict==null || Integer.parseInt(tSysDict.getDictCode()) == 1){
            criteria.andAccountIdEqualTo(accountExtend.getAccountId());
        }

        /* 关键字 **/
        if(searchClientDO.getKeyWord()!=null && !"".equals(searchClientDO.getKeyWord().trim()) ){
            criteria.andCustomerNameLike('%'+searchClientDO.getKeyWord()+'%');
        }

        /* 排序 **/
        if(searchClientDO.getSort()!=null && !"".equals(searchClientDO.getSort().trim())){
            example.setOrderByClause("create_time "+ searchClientDO.getSort());
        }
        PageHelper.startPage(searchClientDO.getPageIndex(), searchClientDO.getPageSize());
        PageInfo<TMiCustomer> pageInfo = new PageInfo<>(customerService.selectByExample(example));


        result.setData(pageInfo);
        result.setMessage("查询代理商医院信息成功。");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /**
     * 客户信息管理-获取客户访问记录
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取客户访问记录", isSaveRequestData = false)
    @ApiOperation(value = "获取客户访问记录", notes = "获取客户访问记录")
    @PostMapping(value = "/customerVisitList")
    public ResponseEntity<HttpDataResult<List<CustomerVistitContactsVO>>> customerVisitList(
            @RequestBody String id,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<List<CustomerVistitContactsVO>> result = new HttpDataResult<>(request.getRequestURI());
        List<CustomerVistitContactsVO> list = new ArrayList<>();

        TMiCustomerVisitExample visitExample = new TMiCustomerVisitExample();
        visitExample.createCriteria().andCustomerIdEqualTo(id);
        visitExample.setOrderByClause("create_time DESC");
        List<TMiCustomerVisit> customerVisitList = customerVisitService.selectByExample(visitExample);

        if(customerVisitList!=null && !customerVisitList.isEmpty()){
            List<String> contactIdList = customerVisitList.stream().map(TMiCustomerVisit::getContactsId).collect(Collectors.toList());
            TMiCustomerContactsExample contactsExample = new TMiCustomerContactsExample();
            contactsExample.createCriteria().andContactsIdIn(contactIdList);
            List<TMiCustomerContacts> customerContacts = customerContactsService.selectByExample(contactsExample);
            Map<String,TMiCustomerContacts> map = new HashMap<>();
            for (TMiCustomerContacts customerContact : customerContacts) {
                map.put(customerContact.getContactsId(),customerContact);
            }

            for (TMiCustomerVisit customerVisit : customerVisitList) {
                list.add(new CustomerVistitContactsVO(customerVisit,map.get(customerVisit.getContactsId())));
            }
        }

        result.setData(list);
        result.setMessage("获取客户访问记录成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息管理-删除客户访问记录
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.DELETE, detail = "删除客户访问记录", isSaveRequestData = false)
    @ApiOperation(value = "删除客户访问记录", notes = "删除客户访问记录")
    @PostMapping(value = "/deleteVisitRecord")
    public ResponseEntity<HttpDataResult<Boolean>> deleteVisitRecord(
            @RequestBody String visitId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());
        customerVisitService.deleteByPrimaryKey(visitId);

        result.setData(true);
        result.setMessage("删除客户访问记录成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息管理-获取客户详细信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取客户详细信息", isSaveRequestData = false)
    @ApiOperation(value = "获取客户详细信息", notes = "获取客户详细信息")
    @PostMapping(value = "/customerDetail")
    public ResponseEntity<HttpDataResult<TMiCustomerVO>> customerDetail(
            @RequestBody String customerId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<TMiCustomerVO> result = new HttpDataResult<>(request.getRequestURI());

        TMiCustomerVO vo = new TMiCustomerVO();
        TMiCustomer customer = customerService.selectByPrimaryKey(customerId);
        if(customer!=null){
            BeanUtils.copyProperties(customer,vo);
            vo.setCreateDate(customer.getCreateTime().toLocalDate());
            TMiCustomerContactsExample contactsExample = new TMiCustomerContactsExample();
            contactsExample.createCriteria().andCustomerIdEqualTo(customerId);
            contactsExample.setOrderByClause("is_default DESC");
            List<TMiCustomerContacts> contcats = customerContactsService.selectByExample(contactsExample);
            vo.setContactList(contcats);
        }else{
            throw new CheckException("该客户不存在！");
        }

        result.setData(vo);
        result.setMessage("获取客户详细信息成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }




    /**
     * 客户信息管理-检查是否有拜访信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "检查是否有拜访信息", isSaveRequestData = false)
    @ApiOperation(value = "检查是否有拜访信息", notes = "检查是否有拜访信息")
    @PostMapping(value = "/checkHasVisit")
    public ResponseEntity<HttpDataResult<Boolean>> checkHasVisit(
            @RequestBody String contactId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        boolean checkResult = false;

        TMiCustomerVisitExample example = new TMiCustomerVisitExample();
        example.createCriteria().andContactsIdEqualTo(contactId);
        List<TMiCustomerVisit> customerVisits = customerVisitService.selectByExample(example);
        if(customerVisits!=null && !customerVisits.isEmpty()){
            checkResult = true;
        }

        result.setData(checkResult);
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息管理——修改客户信息
     * @param customerDO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.UPDATE,detail="提修改客户信息")
    @ApiOperation(value = "提修改客户信息", notes = "提修改客户信息")
    @ApiParam( type = "TMiCustomerDO",name = "customerDO", value = "客户对象", required = true)
    @PostMapping(value = "/editCustomer")
    public ResponseEntity<HttpDataResult<Boolean>> editCustomer(
            @RequestBody @Valid TMiCustomerDO customerDO, BindingResult results,
            HttpServletRequest request, HttpServletResponse response) throws Exception{
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        if (results.hasErrors()){
            throw new CheckException(Objects.requireNonNull(results.getFieldError()).getDefaultMessage());
        }

        TMiCustomer customer = customerService.selectByPrimaryKey(customerDO.getCustomerId());
        if (customer==null){
            throw new CheckException("该客户不存在，无法修改客户信息！");
        }

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        String accountId = accountExtend.getAccountId();


        if(!checkCrossMonth(customer.getCreateTime())){
            //修改基础信息
            TMiCustomer customerUpdate = new TMiCustomer();
            BeanUtils.copyProperties(customer,customerUpdate);
            customerUpdate.setCustomerId(customer.getCustomerId());
            customerUpdate.setAreasCode(customerDO.getAreasCode());
            customerUpdate.setCustomerName(customerDO.getCustomerName());
            customerUpdate.setCustomerAdress(customerDO.getCustomerAdress());
            customerUpdate.setBusiness(customerDO.getBusiness());
            customerUpdate.setRegion(customerDO.getRegion());
            customerUpdate.setNet(customerDO.getNet());
            customerUpdate.setLevel(customer.getLevel());
            customerUpdate.setBelongTo(customerDO.getBelongTo());
            customerUpdate.setModifyTime(LocalDateTime.now());
            customerUpdate.setReviser(accountId);

            customerService.updateByPrimaryKey(customerUpdate);
        }

        result.setData(true);
        result.setMessage("修改客户信息成功。");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /**
     * 客户信息管理-更新联系人信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.UPDATE, detail = "更新联系人信息", isSaveRequestData = false)
    @ApiOperation(value = "更新联系人信息", notes = "更新联系人信息")
    @PostMapping(value = "/updateContact")
    public ResponseEntity<HttpDataResult<Boolean>> updateContact(
            @RequestBody TMiCustomerContacts contact,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        TMiCustomerContacts oldContact = customerContactsService.selectByPrimaryKey(contact.getContactsId());
        if(oldContact!=null){
            oldContact.setContactsName(contact.getContactsName());
            oldContact.setPost(contact.getPost());
            oldContact.setTelephone(contact.getTelephone());
            customerContactsService.updateByPrimaryKey(oldContact);
        }

        result.setData(true);
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息管理-添加联系人信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.INSERT, detail = "addContact", isSaveRequestData = false)
    @ApiOperation(value = "添加联系人信息", notes = "添加联系人信息")
    @PostMapping(value = "/addContact")
    public ResponseEntity<HttpDataResult<TMiCustomerContacts>> addContact(
            @RequestBody TMiCustomerContacts contact,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<TMiCustomerContacts> result = new HttpDataResult<>(request.getRequestURI());

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        String accountId = accountExtend.getAccountId();

        TMiCustomerContactsExample example = new TMiCustomerContactsExample();
        example.createCriteria().andCustomerIdEqualTo(contact.getCustomerId()).andTelephoneEqualTo(contact.getTelephone().trim());
        List<TMiCustomerContacts> customerContacts = customerContactsService.selectByExample(example);
        if(customerContacts!=null && !customerContacts.isEmpty()){
            throw new CheckException("联系人存在重复手机号");
        }

        contact.setContactsId(CommonUtils.randomUUID());
        contact.setCreator(accountId);
        contact.setCreateTime(LocalDateTime.now());
        customerContactsService.insert(contact);

        result.setData(contact);
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息管理-删除联系人信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.DELETE, detail = "deleteContant", isSaveRequestData = false)
    @ApiOperation(value = "删除联系人信息", notes = "删除联系人信息")
    @PostMapping(value = "/deleteContant")
    public ResponseEntity<HttpDataResult<Boolean>> deleteContant(
            @RequestBody String contactsId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        customerContactsService.deleteByPrimaryKey(contactsId);

        result.setData(true);
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息管理-升级客户
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.UPDATE, detail = "升级客户", isSaveRequestData = false)
    @ApiOperation(value = "升级客户", notes = "升级客户")
    @PostMapping(value = "/upgradeCustomer")
    public ResponseEntity<HttpDataResult<Boolean>> upgradeCustomer(
            @RequestBody String customerId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        if(Integer.parseInt(accountExtend.getAccountLevel())>=2){
            TMiCustomer customer = customerService.selectByPrimaryKey(customerId);
            if(customer!=null){
                Integer level = customer.getLevel();
                if(level<5){
                    customer.setLevel(level+1);
                    customerService.updateByPrimaryKey(customer);
                    TMiCustomerUpgrade upgrade = new TMiCustomerUpgrade();
                    upgrade.setUpgradeId(CommonUtils.randomUUID());
                    upgrade.setCustomerId(customer.getCustomerId());
                    upgrade.setBeforeLevel(level);
                    upgrade.setUpgradeLevel(level+1);
                    upgrade.setUpgradeType("1");
                    upgrade.setIsEnable("1");
                    upgrade.setCreator(accountExtend.getAccountId());
                    upgrade.setCreateTime(LocalDateTime.now());
                    upgradeService.insertSelective(upgrade);
                }
            }
        }else{
            throw new CheckException("用户无升级权限");
        }

        result.setData(true);
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 客户信息管理-降级客户
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.UPDATE, detail = "降级客户", isSaveRequestData = false)
    @ApiOperation(value = "降级客户", notes = "降级客户")
    @PostMapping(value = "/downgradeCustomer")
    public ResponseEntity<HttpDataResult<Boolean>> downgradeCustomer(
            @RequestBody String customerId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        TMiAccountExtend accountExtend = (TMiAccountExtend)request.getSession().getAttribute(SessionAttributeEnum.CURRENT_ACCOUNT_EXTEND_INFO.getKey());
        if(Integer.parseInt(accountExtend.getAccountLevel())>=2){
            TMiCustomer customer = customerService.selectByPrimaryKey(customerId);
            if(customer!=null){
                Integer level = customer.getLevel();
                if(level>1){
                    customer.setLevel(level-1);
                    customerService.updateByPrimaryKey(customer);
                    TMiCustomerUpgrade upgrade = new TMiCustomerUpgrade();
                    upgrade.setUpgradeId(CommonUtils.randomUUID());
                    upgrade.setCustomerId(customer.getCustomerId());
                    upgrade.setBeforeLevel(level);
                    upgrade.setUpgradeLevel(level-1);
                    upgrade.setUpgradeType("2");
                    upgrade.setIsEnable("1");
                    upgrade.setCreator(accountExtend.getAccountId());
                    upgrade.setCreateTime(LocalDateTime.now());
                    upgradeService.insertSelective(upgrade);
                }
            }
        }else{
            throw new CheckException("用户无升级权限");
        }

        result.setData(true);
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /***
     *  删除客户
     * @param customerId
     * @param request
     * @param response
     * @return
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.DELETE, detail = "删除客户")
    @ApiOperation(value = "删除客户", notes = "删除客户")
    @ApiImplicitParam(dataType = "String", name = "customerId", value = "代理商id")
    @PostMapping(value = "/delete")
    public ResponseEntity<HttpDataResult<Boolean>> delete(
            @RequestBody String customerId,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());


        if (null == customerId || "".equals(customerId.trim())) {
            throw new CheckException("删除失败，需要删除的客户不存在！");
        }
        TMiCustomer customer = customerService.selectByPrimaryKey(customerId);
        if (customer == null) {
            throw new CheckException("删除失败，需要删除的客户不存在！");
        }
        //判断跨月
        if(checkCrossMonth(customer.getCreateTime())){
            throw new CheckException("已跨月，不允许删除！");
        }
        //判断等级
        if(customer.getLevel()>=2){
            throw new CheckException("等级超过二级，不允许删除！");
        }

        //判断是否存在拜访记录
        TMiCustomerVisitExample customerVisitExample = new TMiCustomerVisitExample();
        customerVisitExample.createCriteria().andCustomerIdEqualTo(customerId);

        if (customerVisitService.countByExample(customerVisitExample) > 0) {
            throw new CheckException("已存在拜访记录，不允许删除！");
        }

        customerService.deleteByPrimaryKey(customerId);
        TMiCustomerUpgradeExample upgradeExample = new TMiCustomerUpgradeExample();
        upgradeExample.createCriteria().andCustomerIdEqualTo(customerId);
        upgradeService.deleteByExample(upgradeExample);
        TMiCustomerContactsExample contactsExample = new TMiCustomerContactsExample();
        contactsExample.createCriteria().andCustomerIdEqualTo(customerId);
        customerContactsService.deleteByExample(contactsExample);
        TMiCustomerTransferExample customerTransferExample = new TMiCustomerTransferExample();
        customerTransferExample.createCriteria().andCustomerIdEqualTo(customerId);
        customerTransferService.deleteByExample(customerTransferExample);


        result.setData(true);
        result.setMessage("OK");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 获取百度OCR的Apikey和SercretKey
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "获取百度OCR的Apikey和SercretKey", isSaveRequestData = false)
    @ApiOperation(value = "获取百度OCR的Apikey和SercretKey", notes = "获取百度OCR的Apikey和SercretKey")
    @GetMapping(value = "/baiduOCR")
    public ResponseEntity<HttpDataResult<BaiduOCRVO>> baiduOCR(
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<BaiduOCRVO> result = new HttpDataResult<>(request.getRequestURI());

        BaiduOCRVO vo = new BaiduOCRVO();

        List<String> list = new ArrayList<>();
        list.add("ocr_api_key");
        list.add("ocr_secret_key");

        TSysConfigExample example = new TSysConfigExample();
        example.createCriteria().andConfigCodeIn(list);
        List<TSysConfig> tSysConfigs = configService.selectByExample(example);
        if(tSysConfigs!=null && !tSysConfigs.isEmpty()){
            for (TSysConfig tSysConfig : tSysConfigs) {
                if("ocr_api_key".equals(tSysConfig.getConfigCode())){
                    vo.setApiKey(tSysConfig.getConfigValue());
                }
                if("ocr_secret_key".equals(tSysConfig.getConfigCode())){
                    vo.setSecretKey(tSysConfig.getConfigValue());
                }
            }
        }
        result.setData(vo);
        result.setMessage("获取百度OCR的Apikey和SercretKey成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /** 检查跨月 **/
    private static Boolean checkCrossMonth(LocalDateTime lastTime) {
        LocalDateTime nowTime = LocalDateTime.now();
        if(lastTime.compareTo(nowTime)>0){
            return false;
        }
        return lastTime.getYear() != nowTime.getYear() || lastTime.getMonthValue() != nowTime.getMonthValue();
    }

    private List<String> getAreaCodeList(String firstAccountLevel,TMiAccountExtend accountExtend){
        List<String> areaCodeList = new ArrayList<>();
        if(firstAccountLevel.equals(accountExtend.getAccountLevel())){
            //业务员
            String areasCode = accountExtend.getAreasCode();
            areaCodeList.add(areasCode);
        }{
            //区域管理员
            String regionCode = accountExtend.getRegionCode();
            if(!StringUtils.isBlank(regionCode)){
                TMiRegionDetailExample example = new TMiRegionDetailExample();
                example.createCriteria().andRegionIdEqualTo(regionCode);
                List<TMiRegionDetail> regionDetailList = regionDetailService.selectByExample(example);
                if(regionDetailList != null && !regionDetailList.isEmpty()){
                    areaCodeList = regionDetailList.stream().map(TMiRegionDetail::getAreasCode).collect(Collectors.toList());
                }
            }
        }
        return areaCodeList;
    }

    private List<TSysDict> getAccountLevel(){
        //区域等级字典表
        List<TSysDict> dictList = dictService.selectByDictTypeId(DictTypeEnum.ACCOUNT_LEVEL_TYPE_GROUP.getId());
        if(dictList==null || dictList.isEmpty()){
            throw new CheckException("区域等级未配置字典表");
        }
        return dictList;
    }
}
